package com.yuanrui.interview.server.interceptor;

import com.yuanrui.interview.server.util.LoginUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 * 当两个服务之间调用时，可以在这里添加一些拦截器，拼接一些参数
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 这里可以添加一些参数
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)) {
            HttpServletRequest request = requestAttributes.getRequest();
            String loginId = request.getHeader("loginId");
            if (Objects.nonNull(loginId)) {
                requestTemplate.header("loginId", loginId);
            } else {
                requestTemplate.header("loginId", LoginUtil.getLoginId());
            }
        }
    }
}
